package com.gk.panda.apis.patrol.servicr.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gk.panda.apis.patrol.commons.RedisUtils;
import com.gk.panda.apis.patrol.commons.StateEnum;
import com.gk.panda.apis.patrol.commons.WeatherConfig;
import com.gk.panda.apis.patrol.controller.client.WeatherController;
import com.gk.panda.apis.patrol.servicr.WeatherService;
import com.gk.panda.commons.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author：xxz
 * @Create: 2022/11/2 18:29
 */
@Service
public class WeatherServiceImpl implements WeatherService {



    @Autowired
    private WeatherConfig weatherConfig;

    @Autowired
    private RedisUtils redisUtils;

    public static final String KEY = "weather:";


    @Override
    public Result<?> getWeather(String lon, String lat) {
        try {
            if (lon.equals("0") || lat.equals("0")){
                return Result.ok();
            }
            String areaId = getAreaId(lon, lat);
            String weatherStr = redisUtils.get(KEY + areaId);
            // redis中存在同城市的天气直接返回天气信息
            if (!StringUtils.isEmpty(weatherStr)){
                return Result.ok(JSONObject.parseObject(weatherStr));
            }
            // 根据城市id获取天气信息
            String url = "https://devapi.qweather.com/v7/weather/now?location=" + areaId + "&key=" + weatherConfig.getKey();
            String weatherRequest = HttpUtil.get(url);

            JSONObject jsonObject = JSONObject.parseObject(weatherRequest, JSONObject.class);
            if (!StringUtils.isEmpty(weatherRequest) && "200".equals(jsonObject.getString("code"))){
                JSONObject now = jsonObject.getObject("now", JSONObject.class);
                // 30分钟后过期
                redisUtils.set(KEY + areaId, now, 30 * 60);
                return Result.ok(now);
            }else {
                return Result.write(StateEnum.RESULT_CODE.ERROR.getCode(), "获取天气信息失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.write(StateEnum.RESULT_CODE.ERROR.getCode(), "获取天气信息失败");
        }

    }

    @Override
    public String getAreaId(String lon, String lat) {
        // todo 是否需要进行坐标转换
        String url = "https://geoapi.qweather.com/v2/city/lookup?location=" + lon + "," + lat + "&key=" + weatherConfig.getKey();
        String request = HttpUtil.get(url);

        JSONObject data = JSONObject.parseObject(request, JSONObject.class);
        JSONArray location = data.getJSONArray("location");

        return location.getObject(0,JSONObject.class).getString("id");
    }
}
